﻿using System.Collections.Generic;
using System.Linq;
using IapApp.Manager;
using NHibernate;

namespace IapService.Data
{
    public class Data<T> where T : class
    {
        protected readonly ISession Session = new DaoManager()
            .OpenSession<Global>("iap", "MySQLString");

        public T Get(int id)
        {
            T item;
            using (var session = Session)
            {
                item = session.Get<T>(id);
            }
            return item;
        }


        public List<T> Get()
        {
            List<T> items;
            using (var session = Session)
            {
                items = session.CreateCriteria<T>()
                    .List<T>()
                    .ToList();
            }
            return items;
        }

        public T Save(T item)
        {
            using (var session = Session)
            {
                session.SaveOrUpdate(item);
                session.Flush();
            }
            return item;
        }

        public T Remove(T item)
        {
            using (var session = Session)
            {
                session.Delete(item);
                session.Flush();
            }
            return item;
        }
    }
}